#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月19日

@author: Administrator
'''
from article import settings
from article.models import Article
from common.decorators import login_required
from common.utils import es
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from elasticsearch_dsl.query import Q
from elasticsearch_dsl.search import Search
from funcresource.decorators import user_funcresource
import copy
import ujson as json

@login_required
@user_funcresource
def index(request, template="article/admin/article/article.html"):
    """
        func:
                               文章列表页面
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    return TemplateResponse(request, template, rsp_data)
    
@login_required
def list(request):
    """
        func:
                               用户列表
        parameters:
            start:开始下标
            length:每页展示个数
            search[value]:搜索关键字
            columns[6][search][value]:用户状态
            draw:渲染次数
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = []
    start = int(request.POST['start'])
    length = int(request.POST['length'])
    keyword = request.POST["search[value]"]
    state = request.POST.get("columns[5][search][value]", "")
    state = '' if state == '' else state[1:-1]
    source = request.POST.get("columns[3][search][value]", "")
    source = '' if source == '' else source[1:-1]
    draw = request.POST['draw']
    #es连接
    response = Search(using=es.es_client, index=settings.ES_INDEX_ARTICLE_LIST, doc_type=settings.ES_INDEX_ARTICLE_LIST_TYPE) 
    if  keyword:
        response = response.query(Q("match_phrase", topic=keyword)) 
    if  state:
        response = response.query(Q("term", state=state)) 
    if  source:
        response = response.query(Q("term", source=source)) 
    response = response.extra(from_=start, size=length) 
    response = response.sort("-id")
    result = response.execute()
    for hit in result.hits:
        record = {
            "id":hit.id,
            "user_name":hit.user_name,
            "topic":hit.topic,
            "source":settings.SOURCE_CHOICES[hit.source][1],
            "source_id":hit.source_id,
            "state_desc":settings.get_state_desc(hit.state),
            "source_url":"%s%s/" % (settings.SOURCE_URL_CHOICES[hit.source][1], hit.source_id),
        }
        rsp_data["data"].append(record)

    rsp_data["recordsTotal"] = result.hits.total
    rsp_data["recordsFiltered"] = result.hits.total
    rsp_data["draw"] = draw
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

    
@login_required
def detail(request, template="article/admin/article/detail.html"):
    """
        func:
                               文章详情页面
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["article"] = {}
    article_id = request.GET["article_id"]
    try:
        article = Article.objects.get(id=article_id, state=settings.StateEnum.VALID)
    except Article.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    rsp_data["data"]["article"]["id"] = article_id
    rsp_data["data"]["article"]["topic"] = article.topic
    rsp_data["data"]["article"]["first_name"] = article.user.first_name
    rsp_data["data"]["article"]["avatar_url"] = article.user.profile.avatar_url
    rsp_data["data"]["article"]["create_time"] = article.create_time.strftime('%Y-%m-%d %H:%M:%S')
    return TemplateResponse(request, template, rsp_data)

@login_required
def get_article_content(request):
    """
        func:
                               文章详情页面
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    article_id = request.POST["article_id"]
    try:
        article = Article.objects.get(id=article_id, state=settings.StateEnum.VALID)
    except Article.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    rsp_data["data"]["article_content"] = article.content
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def get_article_source_list(request):
    """
        func:
                               文章详情页面
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = [{"id":source[0], "name":source[1]} for source in settings.SOURCE_CHOICES]
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
